<template>
  <div>
    <quill-editor
      v-model="currentValue"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @change="onEditorChange($event)"
    >
    </quill-editor>
    <input
      type="file"
      v-show="false"
      ref="upload"
      :accept="uploadAccept"
      @change="onFileChange"
    />
  </div>
</template>


<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

// npm install vue-quill-editor
// npm install quill
// npm install quill-image-drop-module
// npm install quill-image-resize-module
import Quill from "quill";
import ImageResize from "quill-image-resize-module"; // 引用
import { ImageDrop } from "quill-image-drop-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize); // 注册

let imageUrl = null;

export default {
  components: {
    "quill-editor": quillEditor,
  },
  props: {
    // 编辑器内容值
    value: {
      type: String,
    },
    // 编辑器高度
    height: {
      type: Number,
    },
  },
  data() {
    return {
      uploadAccept: "image/*",
      imageData: null,
      uploadImg: {
        listType: "text",
        accept: "image/png,image/jpg,image/jpeg",
      },
      // 当前内容值
      currentValue:
        this.value === undefined || this.value === null ? "" : this.value,
      // 编辑器配置选项
      editorOption: {
        placeholder: "请输入文本……",
        // 模块
        modules: {
          // 拖拽插入图片
          imageDrop: true,
          //改变图片大小
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
          // 工具栏配置
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], // 引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], // 列表
            [{ script: "sub" }, { script: "super" }], // 上下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], // 字体
            [{ align: [] }], // 对齐方式
            ["clean"], // 清除字体样式
            ["image", "video"], // 上传图片、上传视频
          ],
        },
      },
    };
  },
  watch: {
    value(newVal) {
      this.currentValue = newVal;
    },
    currentValue(newVal) {
      this.currentValue = newVal;

      if (this.value != newVal) {
        this.$emit("input", newVal);
      }
    },
    height(newVal) {
      this.setEditorHeight(newVal);
    },
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  methods: {
    onFileChange(event) {
      let filelist = event.target.files;
      if (filelist.length == 0) {
        return this.$notify.error("请选择需要上传的图片");
      }

      let file = filelist[0];
      let action = "/fileAPI";
      if (process.env.NODE_ENV != "development") {
        action = this.$store.getters.config.uploadURL;
      }
      var form = new FormData();
      // 文件对象
      form.append("files", file);
      // 文件对象
      form.append("Folder", this.$store.getters.config.uploadFolder);

      //开始上传
      this.$http.post(action, form, (res) => {
        if (res.status) {
          let url = imageUrl + res.data[0].storageName;
          // 获取光标所在位置
          let length = this.editor.getSelection().index;
          // 插入图片 res.info为服务器返回的图片地址
          if (this.uploadAccept == "image/*") {
            this.editor.insertEmbed(length, "image", url);
          } else if (this.uploadAccept == "video/*") {
            this.editor.insertEmbed(length, "video", url);
          }
          // 调整光标到最后
          this.editor.setSelection(length + 1);
        }
      });
    },
    // 设置编辑器的高度
    setEditorHeight(height) {
      height = height || 350;

      this.editor.container.style.height = `${height}px`;
    },
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
  },
  created() {
    imageUrl =
      this.$store.getters.config.uploadImage +
      this.$store.getters.config.uploadFolder +
      "/";
  },
  mounted() {
    let imgHandler = async (image) => {
      if (image) {
        this.uploadAccept = "image/*";
        this.$nextTick(() => {
          this.$refs.upload.click();
        });
      }
    };
    this.editor.getModule("toolbar").addHandler("image", imgHandler);

    let videoHandler = async (video) => {
      if (video) {
        this.uploadAccept = "video/*";
        this.$nextTick(() => {
          this.$refs.upload.click();
        });
      }
    };
    this.editor.getModule("toolbar").addHandler("video", videoHandler);
    // 初始化，设置编辑器高度
    this.$nextTick(() => {
      this.setEditorHeight();
    });
  },
};
</script>

<style>
.ql-editor-class {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 1;
  height: 100%;
  outline: none;
  padding: 0 !important;
  tab-size: 4;
  -moz-tab-size: 4;
  text-align: left;
  word-wrap: break-word;
}
</style>